<template>
  <div>
    <!-- <input type="text" v-model="fileName" placeholder="Enter file name" /> -->
    <button @click="startDownload">Start Download</button>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      fileName: "pdfTest.pdf", // 输入的文件名
      chunkSize: 25 * 1024 * 1024, // 分片大小，50MB
      totalSize: 0, // 文件的总大小
      downloadedChunks: [], // 存储下载的分片
      currentChunk: 0, // 当前下载的分片索引
    };
  },
  methods: {
    async startDownload() {
      if (!this.fileName) {
        alert("Please enter a file name.");
        return;
      }

      //获取文件的总大小;
      // const metaDataResponse = await this.$http.get(
      //   `/file/file/fileMetaData?filename=${this.fileName}`
      // );
      const params = { filename: this.fileName };
      const metaDataResponse = await this.$http.get("/file/file/fileMetaData", {
        params,
      });

      // const metaDataResponse = await this.$http.get("/file/file/fileMetaData", {
      //   params: this.fileName,
      // });
      this.totalSize = metaDataResponse.data.data.fileSize;

      // 计算分片数量
      const totalChunks = Math.ceil(this.totalSize / this.chunkSize);

      // 构建所有分片下载任务
      const downloadTasks = [];
      for (let i = 0; i < totalChunks; i++) {
        downloadTasks.push(this.downloadChunk(i));
      }

      // 并行下载所有分片
      await Promise.all(downloadTasks);

      // 合并分片
      this.mergeChunks();
    },

    async downloadChunk(index) {
      const start = index * this.chunkSize;
      const end = Math.min(start + this.chunkSize - 1, this.totalSize - 1);
      const range = `bytes=${start}-${end}`;
      console.log("Downloading range:", range);

      try {
        // const response = await this.$http.get(`/file/fileDownload`, {
        //   params: {
        //     filename: this.fileName,
        //     range: range,
        //   },
        //   responseType: "blob",
        // });
        console.log("111111111" + this.fileName);
        const encodedFileName = this.fileName;
        const url = `/file/file/fileDownload?filename=${this.fileName}&range=bytes=${start}-${end}`;
        const response = await this.$http.get(url, {
          responseType: "blob",
        });

        if (response.data.size !== end - start + 1) {
          console.error(`Chunk ${index} downloaded with incorrect size`);
          throw new Error(`Chunk ${index} downloaded with incorrect size`);
        }

        this.downloadedChunks[index] = response.data;
        console.log(`Chunk ${index} downloaded successfully`);
        this.currentChunk = index + 1;
      } catch (error) {
        console.error("Error downloading chunk:", error);
        // 重试下载
        this.downloadChunk(index);
      }
    },

    mergeChunks() {
      if (
        this.downloadedChunks.length !==
        Math.ceil(this.totalSize / this.chunkSize)
      ) {
        console.error("Not all chunks are downloaded");
        return;
      }

      const blob = new Blob(this.downloadedChunks, {
        type: "application/octet-stream",
      });
      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = this.fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
  },
};
</script>

<style scoped>
input {
  margin-right: 10px;
}
</style>
